/**
 * @file 工单操作-回访
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'rate', 'list_modify_common', '$http', 'Vue'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var rate = layui.rate;
    var opCommonUtils = layui.list_modify_common;
    var layer = layui.layer;
    var $http = layui.$http;
    var Vue = layui.Vue;

    var ALREADY_EVALUATED = 2;

    var isEvaluated = replyVisitVO.commentStatus === ALREADY_EVALUATED;

    var arrQuestions = [];

    var SAVE_REPLY_URL = '/work/modify/save/reply/visit.action';
    var GET_COMMENT_MAP_URL = '/order_comment/commentCodeMapList.action';

    var questionVM = new Vue({
        el: '#question',
        template: '#reply-request-tmpl',
        data: function () {
            return {
                itemId: undefined,
                replyVisitList: replyVisitVO.replyVisitList
            };
        },
        computed: {
            questionList: function () {
                var itemId = Number(this.itemId);
                return this.replyVisitList.filter(function (item) {
                    return item.items.includes(itemId) ;
                });
            }
        },
        watch: {
            'questionList': function () {
                arrQuestions = this.questionList;
            }
        },
        updated: function () {
            form.render();
        }
    });


    /**
     * 验证表单
     */
    function initFormVerify () {
        form.verify({
            length: function (value) {
                if (value.length > 1000) {
                    return '评价内容不能大于1000字'
                }
            },
            // 必填校验
            otherReq: function(value,item){
                var $ = layui.$;
                var verifyName=$(item).attr('name')
                    , verifyType=$(item).attr('type')
                    ,formElem=$(item).parents('.layui-form')//获取当前所在的form元素，如果存在的话
                    ,verifyElem=formElem.find('input[name='+verifyName+']')//获取需要校验的元素
                    ,isTrue= verifyElem.is(':checked')//是否命中校验
                    ,focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
                if(!isTrue || !value){
                    //定位焦点
                    focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
                    //对非输入框设置焦点
                    focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {
                        focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
                    }).focus();
                    return '必填项不能为空';
                }
            }
        })
    }

    /**
     * 提示消息;
     * @param str {string} 显示的消息
     */
    function toast(str) {
        layer.msg(str);
    }

    /**
     * 提交条件检查
     * @type {Function}
     */
    var preSubmissionVerification = (function () {
        /**
         * 判断订单评价是否有复选框被选中;
         * @param ele{string}复选框的dom元素
         * @returns {boolean}
         */
        function isCheckReply(ele) {
            return !($(ele).find(':checked').length === 0);
        }

        /**
         * 判断文本域是否为空
         * @param ele{string} textarea的dom元素
         * @returns {boolean}
         */
        function isTextarea(ele) {
            var a = $(ele).val();
            return !!a;
        }

        function isCheckReplyVisit(ele) {
            return !($(ele).find(':checked').length === 0);
        }

        /**
         * 订单评价/订单选择评价 必有其一
         * @returns {boolean}
         */
        function alternativerReply() {
            return isCheckReply("#orderEvaluation") || isTextarea(".d-reply-textarea");
        }

        /**
         * 回访选择内容/回访填入内容 必有其一
         * @returns {boolean}
         */
        function alternativerVisit() {
            return isCheckReplyVisit("#reply-request-wrapper") || isTextarea(".d-visit-textarae");
        }

        return function () {
            var star = $('input[name=score]').val();
            if (replyVisitVO.shouldComment == 2) {
                if (star < 1 && !isEvaluated) {
                    toast('请选择评星');
                    return false;
                }

                if (star < 5) {//小于5星 订单选择/订单评价至少一个
                    if (!alternativerReply() && !isEvaluated) {
                        toast('请选择订单评价或填写订单评价');
                        return false;
                    }
                }
            }
            if (!alternativerVisit()) {
                toast('请选择回访内容或填写回访内容');
                return false;
            }
            return true;
        };
    })();

    function _getInputTitleByNameAndValue (name, value) {
        return $('input[name="' + name + '"][value="' + value + '"]').attr('title');
    }

    /**
     * 提交字段处理
     * @param data
     */
    function _normalizeSubmitParams (dataObj) {
        var params = {
            commentCodeMapList: [],
            replyVisitList: []
        };

        var formDataArr = $(dataObj.form).serializeArray();

        formDataArr.forEach(({ name, value }) => {
            if (name === 'commentCodeMapList') {
                params.commentCodeMapList.push({
                    text: _getInputTitleByNameAndValue(name, value),
                    value: value
                });

                return;
            }

            if (params[name]) {
                params[name] += ',' + value;
            } else {
                params[name] = value;
            }
        });


        // 拼装回访数据
        arrQuestions.forEach(function (que) {
            if (params[que.questionId]) {
                params.replyVisitList.push({
                    value: que.questionId,
                    text: que.question,
                    ext1: params[que.questionId]
                });
                delete params[que.questionId];
            }
        });
        return params;
    }

    /**
     * 提交
     * @param data
     */
    function submit (params, button) {
        $http.lockSave(SAVE_REPLY_URL, params, button).then(function () {
            layer.msg('操作成功', { icon: 1, time: 1000 }, function () {
                opCommonUtils.goOperateHome();
            });
        }, (msg) => {
            layer.msg(msg);
        });
    }

    function conmentMapHtml(score, binType, binLine) {
        $.ajax({
            type: "get",
            url: GET_COMMENT_MAP_URL,
            data: {score: score,binType: binType, binLine: binLine},
            success: function (resultData) {
                if (resultData.statusBool) {
                    if (resultData.data === undefined) {
                        resultData.data = [];
                    }
                    var data = resultData.data;
                    // 过滤搜索结果
                    let html = '';
                    data.forEach(function (value, index, array) {
                        html += '<div class="layui-col-xs12 layui-col-sm6 layui-col-md3">' +
                            '<input type="checkbox" lay-skin="primary" name="commentCodeMapList" title="' + value.text + ' "value="' + value.value + '">' +
                            '</div>';
                    });
                    $('#comment_map_div').html(html);
                    form.render();
                }
            }
        });
    }

    /**
     * 初始化页面评分组件
     */
    function _initCommentStar () {
        rate.render({
            elem: '#rate',
            theme: '#f88b00',
            value: replyVisitVO.score,
            readonly: replyVisitVO.score !== null,
            choose: function (val) {
                $('input[name=score]').val(val);
                conmentMapHtml(val, replyVisitVO.bizType, replyVisitVO.bizLine);
            }
        });
        conmentMapHtml(replyVisitVO.score, replyVisitVO.bizType, replyVisitVO.bizLine);
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        // 监听保存按钮
        form.on('submit()', function (data) {

            if (!preSubmissionVerification()) {
                return false;
            }
            var params = _normalizeSubmitParams(data);
            submit(params, data.elem);
            return false;
        });

        // 回访类别
        form.on("select(itemId)", function (data) {
            questionVM.$set(questionVM.$data, 'itemId', data.value);
            form.render();
        });

    }

    /**
     * 初始化页面
     */
    function initPage() {
        _initCommentStar();

        // 验证表单
        initFormVerify();
    }

    // 程序入口
    function init() {
        // 初始化事件
        initEvent();

        // 初始化页面
        initPage();
    }

    // 初始化
    init();

    exports('oms_work_modify_replyvisit');
});
